<template>
  <div id="index">
    <div class="item" v-for="(v,i) in os_data" :key="v.type">
      <div class="title">{{ v.title }}{{ v.percent }}{{ v.unit }}</div>
      <div class="line_box">
        <div class="line" :class="v.class_color" :style="{width:`${v.percent}${v.unit}`}"></div>
      </div>
    </div>
  </div>
</template>
<script>
import {get_cpu_usage, get_storage_usage} from "../util/get_os_state";
import {ref, reactive} from 'vue'

export default {
  name: "index",
  setup() {
    const os_data = reactive({
      cpu: {
        type: 'cpu',
        title: 'cpu占用：',
        percent: 0,
        unit: '%',
        class_color: 'nice_color'
      },
      mem: {
        type: 'mem',
        title: '内存：',
        percent: 0,
        unit: '%',
        class_color: 'nice_color'
      }
    })
    let ms = 1000

    function set_class_color(num) {
      if (num < 50) {
        return 'nice_color'
      } else if (num >= 50 && num < 75) {
        return 'nervous_color'
      } else {
        return 'warning_color'
      }
    }

    get_cpu_usage(ms, false).then(cpu => {
      let pac_cpu = (cpu * 100).toFixed(2)
      os_data.cpu.class_color = set_class_color(pac_cpu)
      os_data.cpu.percent = pac_cpu
    })
    setInterval(() => {
      get_cpu_usage(ms, false).then(cpu => {
        let pac_cpu = (cpu * 100).toFixed(2)
        os_data.cpu.class_color = set_class_color(pac_cpu)
        os_data.cpu.percent = pac_cpu
      })
      const mem = get_storage_usage()
      let pac_mem = ((mem.usedmem / mem.totalmem) * 100).toFixed(2)
      os_data.mem.class_color = set_class_color(pac_mem)
      os_data.mem.percent = pac_mem
    }, ms)

    return {
      os_data
    }


  },
  mounted() {
    const {exec} = require('child_process');
    exec('tasklist', {encoding:'binary'},function (error, stdout, stderr) {
      if (error) {
        console.error('error: ' + error);
        return;
      }
      stdout.split('\n').filter((line) => {
        let processMessage = line.trim().split(/\s+/)
        let processName = processMessage[0] //processMessage[0]进程名称 ， processMessage[1]进程id
        console.log(processMessage)
      })
      console.log('stderr: ' + typeof stderr);
    });
  },
  methods: {}
}
</script>
<style scoped lang="less">
#index {
  width: 100%;
  height: 100%;
  .line_box {
    width: 100%;
    height: 15px;
    border: 1px solid blue;
    border-radius: 25px;
    margin: 10px auto;
    .line {
      height: 100%;
      //background-color: rgba(255, 255, 0, 0.3);
      transition: width .5s;
      border-radius: 25px;
    }
  }
  .nice_color {
    background-image: linear-gradient(to right, #42bb42, #69e84e);
  }
  .nervous_color {
    background-image: linear-gradient(to right, #96fd07, yellow);
  }
  .warning_color {
    background-image: linear-gradient(to right, #e2de0c, red);
  }
}
</style>